import { Typography, Descriptions, Row, Col, Tag, Image, message, Button, Space, Modal, } from 'antd';
import ProCard from '@ant-design/pro-card';
import React, { useState, useEffect } from 'react';
import { Access, useAccess, history } from 'umi';
import ProTable from '@ant-design/pro-table';
import type { ProColumns } from '@ant-design/pro-table';
import { PageContainer } from '@ant-design/pro-layout';

// 订单接口导入
import { adminOpenCell, changePhone, getDeliveryDetail, getDeliveryLog } from '@/services/delivery';
import { createFromIconfontCN, EditOutlined, RightOutlined } from '@ant-design/icons';
import { ModalForm, ProFormText } from '@ant-design/pro-form';
import { statusData } from '@/utils/common';

const { Title } = Typography;
const checkinModeText = ['手机扫描模式', '手机拍照模式'];
const storeModeText = ['货架', '货架', '柜体', '暂存区'];
const notifyText = [
    {
        label: '短信发送中',
        value: 5
    },
    {
        label: '短信发送成功',
        value: 1
    },
    {
        label: '短信发送失败',
        value: 2
    },
    {
        label: '微信发送中',
        value: 6
    },
    {
        label: '微信发送成功',
        value: 3
    },
    {
        label: '微信发送失败',
        value: 4
    },
];


const MyIcon = createFromIconfontCN({
    scriptUrl: '//at.alicdn.com/t/font_3354826_k42a89lunf.js'
});

const Detail: React.FC = () => {

    // 获取权限
    const access = useAccess();


    const [cur_id, setCur_id] = useState<string>();
    const [nameShow, setNameShow] = useState<boolean>(false);
    const [codeShow, setCodeShow] = useState<boolean>(false);
    const [phoneShow, setPhoneShow] = useState<boolean>(false);

    const [inPutVisible, updInPutVisibleVisible] = useState<boolean>(false);
    const [outBoundVisible, updOutBoundVisible] = useState<boolean>(false);
    const [pictureVisible, updPictureVisible] = useState<boolean>(false);

    const [updPhoneVisible, handleUpdPhoneVisible] = useState<boolean>(false);
    const [rotation, handleUpdRotation] = useState<number>(0);

    const [deliveryDetail, setDeliveryDetail] = useState<any>();
    const [deliveryLog, setDeliveryLog] = useState<any>();


    const l_state: any = history.location.state;
    if (!cur_id && (!l_state || !l_state?.data)) {
        history.push('/order/delivery/list');
    }

    const id: string = l_state?.data.id;
    //  同path更新,只更新state时，通过id重新请求数据
    if (l_state && (!cur_id || cur_id !== id)) {
        setCur_id(id);
    }

    useEffect(() => {

        const getStationDetails = async () => {
            try {
                const msg = await getDeliveryDetail({ id: cur_id });;
                if (msg.code === 0) {
                    let data = {};
                    data = Object.assign({}, msg.body, data);
                    setDeliveryDetail(data);
                    return;
                }
            } catch (error) {
                console.log(error);
            }
        };

        const getDetailLog = async () => {
            try {
                const msg = await getDeliveryLog({ id: cur_id });
                let data = {};
                data = Object.assign({}, msg.body, data);
                setDeliveryLog(msg.body);
            } catch (error) {
                console.log(error);
            }
        };

        getStationDetails();
        getDetailLog();
    }, [id]);

    // 手机扫描模式无
    const getDetailLogImg = async (id: any) => {
        let data = null;
        try {
            const msg = await getDeliveryLog({ id });
            const item = msg.body.find((item: any) => item.op === '入库');
            const explainData = item.explain.split('|');
            if (explainData[1].indexOf('http') > -1) {
                data = explainData[1].substring(explainData[1].indexOf('http'));
            }
        } catch (error) {
            console.log(error);
        }
        return data;
    };

    const log_columns: ProColumns<any>[] = [
        {
            title: '操作时间',
            dataIndex: 'time',
        },
        {
            title: '操作说明',
            dataIndex: 'explain',
            render: (dom, entity, index) => {
                const explainData = entity.explain.split('|');
                let inDom = null, outDom = null;
                if (entity?.op === '出库') {
                    const outData = explainData[1].split(',');

                    if (outData[0] && outData[0].indexOf('http') > -1) {
                        inDom = (<span style={{ cursor: 'pointer', color: '#EFB134' }} onClick={() => {
                            updOutBoundVisible(true);
                        }}>{outData[0].substring(0, outData[0].indexOf('http'))} <Image
                                width={0}
                                style={{ display: 'none' }}
                                src={outData[0].substring(outData[0].indexOf('http'))}
                                preview={{
                                    visible: outBoundVisible,
                                    src: outData[0].substring(outData[0].indexOf('http')),
                                    onVisibleChange: value => {
                                        updOutBoundVisible(value);
                                    },
                                }}
                            /></span>)
                    }

                    if (outData[1] && outData[1].indexOf('http') > -1) {
                        outDom = (<span style={{ cursor: 'pointer', color: '#EFB134' }} onClick={() => {
                            updPictureVisible(true);
                        }}>{outData[1].substring(0, outData[1].indexOf('http'))} <Image
                                width={0}
                                style={{ display: 'none' }}
                                src={outData[1].substring(outData[1].indexOf('http'))}
                                preview={{
                                    visible: pictureVisible,
                                    src: outData[1].substring(outData[1].indexOf('http')),
                                    onVisibleChange: value => {
                                        updPictureVisible(value);
                                    },
                                }}
                            /></span>)
                    }
                } else {
                    if (explainData[1] && explainData[1].indexOf('http') > -1) {
                        inDom = (<span style={{ cursor: 'pointer', color: '#EFB134' }} onClick={() => {
                            updInPutVisibleVisible(true);
                        }}>{explainData[1].substring(0, explainData[1].indexOf('http'))} <Image
                                width={200}
                                style={{ display: 'none' }}
                                src={explainData[1].substring(explainData[1].indexOf('http'))}
                                preview={{
                                    visible: inPutVisible,
                                    src: explainData[1].substring(explainData[1].indexOf('http')),
                                    getContainer: false,
                                    onVisibleChange: value => {
                                        updInPutVisibleVisible(value);
                                    },
                                }}
                            /></span>)
                    } else {
                        inDom = explainData[1];
                    }
                }
                return (
                    <div key={index + 1}>
                        <div>{explainData[0]} {(explainData.length > 1 && inDom) && '|'} {inDom} {outDom}</div>
                        {/* <div style={{ display: 'none', width: "300px", height: "300px", position: "absolute", zIndex: 10 }}>
                            <Image style={{ width: 300, height: 300, }} src={current_Url} preview={{
                                getContainer: false,
                            }} alt="" />
                        </div> */}
                    </div>
                );
            },
        },
        {
            title: '操作人',
            dataIndex: 'oper',
        },
    ];

    const notice_columns: ProColumns<any>[] = [
        {
            title: '通知内容',
            dataIndex: 'content',
        },
        {
            title: '通知方式',
            dataIndex: 'way',
            width: '100px',
        },
        {
            title: '通道名称',
            dataIndex: 'channel',
            width: '120px',
            render: (dom, entity) => {
                return (entity.channel ? <div>{entity.channel}</div> : '--')
            }
        },
        {
            title: '通知状态',
            dataIndex: 'status',
            width: '130px',
            fieldProps: {
                options: notifyText
            },
            render: (dom, entity) => {
                const item = notifyText.find(i => i.value === entity.status);
                return (
                    <div key={entity.id}>
                        {(entity.status > 0 && item?.value) ? <div style={{ color: ([1, 3].includes(item?.value)) ? 'green' : [2, 4].includes(item?.value) ? 'red' : '#333' }}>{item?.label}</div> : <div>--</div>}
                    </div>
                );
            },
        },
        {
            title: '发送时间',
            dataIndex: 'sendTime',
            width: '120px',
        },
        {
            title: '回执时间',
            dataIndex: 'callbackTime',
            width: '120px',
            render: (dom, entity) => {
                return (<div>{entity.callbackTime ? dom : '--'}</div>)
            }
        },
    ];

    // 远程开箱
    const handleOpenCell = async (desc: string, cabId: number) => {
        Modal.confirm({
            className: 'again-send',
            icon: false,
            width: '320px',
            title: (<div style={{ textAlign: 'center', fontSize: 18, color: '#000' }}>提示</div>),
            content: (<div>
                <div style={{ textAlign: 'center', color: 'rgba(136, 136, 136, 100)', fontSize: 15, marginBottom: 12, }}>确定打开格口？</div>
            </div>),
            centered: true,
            maskClosable: true,
            okText: '确认',
            cancelText: '取消',
            onOk: async () => {
                // 打开格口
                const msg = await adminOpenCell({ cellDesc: desc, cabId: cabId, expCode: deliveryDetail?.billNo, cellSide: 2, terminal: 'trench' });
                if (msg.code === 0) {
                    message.success('操作成功');
                }
            }
        });
    }

    // 收费信息dom渲染结构
    const chargeInfoData = (detail: any) => {
        // 是否到付件
        const isFreightCollect = detail?.status?.freightCollect;
        // 取件是否收费
        const isPickUpFree = detail?.payment.pickup.fee === 0;
        // 取回是否收费
        const isRetrieveFree = detail?.payment.retrieve.fee === 0;
        return [
            {
                title: '到付',
                fee: isFreightCollect ? `${(deliveryDetail?.payment.freightCollect.fee / 100)}元` : '非到付件',
                pay: (isFreightCollect ? [1, 2].includes(deliveryDetail?.status.bill) ? '--' : `${(deliveryDetail?.payment.freightCollect.pay / 100)}元` : '非到付件'),
                time: (isFreightCollect ? [1, 2].includes(deliveryDetail?.status.bill) ? '--' : (deliveryDetail?.payment.freightCollect.time || '--') : '非到付件'),
                chargeWay: (isFreightCollect ? ([1, 2].includes(deliveryDetail?.status.bill) ? '--' : (deliveryDetail?.payment.freightCollect.chargeWay || '--')) : '非到付件'),
            },
            {
                title: '取件',
                fee: isPickUpFree ? '免费订单' : `${(deliveryDetail?.payment.pickup.fee / 100)}元`,
                pay: isPickUpFree ? '免费订单' : (deliveryDetail?.payment.pickup?.isPickupFree === 1 && deliveryDetail?.payment.pickup?.pay === 0) ? '白名单用户' : `${(deliveryDetail?.payment.pickup.pay / 100)}元`,
                time: isPickUpFree ? '免费订单' : deliveryDetail?.payment.pickup.time || '--',
                chargeWay: isPickUpFree ? '免费订单' : (deliveryDetail?.payment.pickup.chargeWay || '--'),
            },
            {
                title: '取回',
                fee: isRetrieveFree ? '免费订单' : `${(deliveryDetail?.payment.retrieve.fee / 100)}元`,
                pay: isRetrieveFree ? '免费订单' : `${(deliveryDetail?.payment.retrieve.pay / 100)}元`,
                time: isRetrieveFree ? '免费订单' : deliveryDetail?.payment.retrieve.time || '--',
                chargeWay: isRetrieveFree ? '免费订单' : (deliveryDetail?.payment.retrieve.chargeWay || '--'),
            },
        ]
    }

    return (
        <PageContainer>
            <ProCard style={{ marginTop: 8 }} gutter={8} >
                <Title level={3}>基础信息</Title>
                <Descriptions
                    bordered
                    column={{ xxl: 3, xl: 3, lg: 3, md: 3, sm: 2, xs: 1 }}
                >
                    <Descriptions.Item label="运单号">
                        <div>
                            <div style={{ display: 'inline-block', marginRight: '6px' }}>{deliveryDetail?.billNo}</div>

                            <div style={{ display: 'inline-flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center' }}>
                                <div style={{ marginBottom: 10 }}><Tag visible={deliveryDetail?.status?.inventory} color={'#FF8826'}>待盘点</Tag></div>
                                <div><Tag visible={deliveryDetail?.status?.freightCollect} color={'#f50'}>到付</Tag></div>
                            </div>
                        </div>
                    </Descriptions.Item>
                    <Descriptions.Item label="快递公司">
                        <div>
                            <Image preview={false} width={35} src={deliveryDetail?.express?.logo || ''} />
                            <span style={{ marginLeft: 3 }} >{deliveryDetail?.express?.name}</span>
                        </div>
                    </Descriptions.Item>
                    <Descriptions.Item label="驿站名称">{deliveryDetail?.station?.name}</Descriptions.Item>
                    <Descriptions.Item label="订单状态">{statusData[deliveryDetail?.status.bill - 1]}</Descriptions.Item>
                    <Descriptions.Item label="收件人手机号">
                        <div>
                            {(!deliveryDetail?.receiver.phone && deliveryDetail?.checkinMode === 2) && <div>
                                {/* {deliveryDetail?.status?.ocr === 3 && <div style={{ color: 'red', fontWeight: 'bold' }}>OCR识别失败</div>} */}
                                {deliveryDetail?.status?.ocr === 1 && <div style={{ fontWeight: 'bold' }}>OCR识别中</div>}
                            </div>}
                            <div>
                                {deliveryDetail?.receiver.phone ? (phoneShow ? deliveryDetail?.receiver?.phone : (deliveryDetail?.receiver?.phone.slice(0, 3) + '****' + deliveryDetail?.receiver?.phone.slice(-4))) : '--'}
                                <Access
                                    accessible={access.can_deliveryAll.changePhone}
                                >
                                    {[1, 2].includes(deliveryDetail?.status.bill) && <EditOutlined style={{ marginLeft: 10 }} onClick={async (e) => {
                                        e.stopPropagation();
                                        e.nativeEvent.stopImmediatePropagation();
                                        if (deliveryDetail.checkinMode === 1) {
                                            const img = await getDetailLogImg(deliveryDetail.id);
                                            img && Object.assign(deliveryDetail, { scanImg: img });
                                        }
                                        // 修改手机号弹窗
                                        handleUpdPhoneVisible(true);
                                    }} />}
                                </Access>
                                {deliveryDetail?.receiver?.phone && <MyIcon style={{ marginLeft: 10, fontSize: 18, verticalAlign: 'middle' }} type={phoneShow ? "icon-yanjing_xianshi_o" : "icon-yanjing_yincang_o"} onClick={() => {
                                    setPhoneShow(!phoneShow);
                                }} />}
                            </div>
                            <div><Tag visible={deliveryDetail?.status?.blacklist} color={'#f50'}>黑名单用户</Tag></div>
                        </div>
                    </Descriptions.Item>
                    <Descriptions.Item label="入库模式">{checkinModeText[deliveryDetail?.checkinMode - 1]}</Descriptions.Item>
                    <Descriptions.Item label="客户姓名">
                        <span style={{ marginRight: 10, verticalAlign: 'middle' }}>{deliveryDetail?.receiver.name ? (nameShow ? deliveryDetail?.receiver.name : deliveryDetail?.receiver.name.slice(0, 1) + '**') : '--'}</span>
                        {deliveryDetail?.receiver.name && <MyIcon style={{ fontSize: 18, verticalAlign: 'middle' }} type={nameShow ? "icon-yanjing_xianshi_o" : "icon-yanjing_yincang_o"} onClick={() => {
                            setNameShow(!nameShow);
                        }} />}
                    </Descriptions.Item>
                    <Descriptions.Item label="存储类型">{storeModeText[deliveryDetail?.storeMode - 1]}</Descriptions.Item>
                    <Descriptions.Item label="驿站详细地址">{deliveryDetail?.station.address}</Descriptions.Item>
                    <Descriptions.Item label="取件码">
                        <span style={{ marginRight: 10, verticalAlign: 'middle' }}>{deliveryDetail?.pickupCode ? (codeShow ? deliveryDetail?.pickupCode : '******') : '--'}</span>
                        <MyIcon style={{ fontSize: 18, verticalAlign: 'middle' }} type={codeShow ? "icon-yanjing_xianshi_o" : "icon-yanjing_yincang_o"} onClick={() => {
                            setCodeShow(!codeShow);
                        }} />
                    </Descriptions.Item>
                    <Descriptions.Item label="柜体名称">{deliveryDetail?.storeMode === 3 ? deliveryDetail?.cab.name : '--'}</Descriptions.Item>
                    <Descriptions.Item label="柜体位置">{deliveryDetail?.storeMode === 3 ? deliveryDetail?.cab.addr : '--'}</Descriptions.Item>
                    <Descriptions.Item label="格口编号">{deliveryDetail?.storeMode === 3 ? (
                        <Space>
                            <div>{deliveryDetail?.cell.desc}</div>
                            {![3, 4, 7, 8, 9].includes(deliveryDetail?.status.bill) && <Button type='primary' size={'small'} onClick={() => {
                                handleOpenCell(deliveryDetail?.cell.desc, deliveryDetail?.cab.id);
                            }}>远程开箱<RightOutlined /></Button>}
                        </Space>
                    ) : '--'}</Descriptions.Item>
                    <Descriptions.Item label="柜体编号">{deliveryDetail?.storeMode === 3 ? deliveryDetail?.cab.code : '--'}</Descriptions.Item>
                    <Descriptions.Item label=" "> </Descriptions.Item>
                </Descriptions>
            </ProCard>
            <ProCard style={{ marginTop: 8 }} gutter={8}>
                <Title level={3}>操作日志</Title>
                <ProTable
                    rowKey="time"
                    search={false}
                    pagination={false}
                    toolBarRender={false}
                    dataSource={deliveryLog}
                    columns={log_columns}
                />
            </ProCard>
            <ProCard style={{ marginTop: 8 }} gutter={8}>
                <Title level={3}>收费信息</Title>
                {deliveryDetail && chargeInfoData(deliveryDetail).map(item => {
                    return (<Descriptions
                        style={{ marginTop: 26 }}
                        title={`${item.title}`}
                        bordered
                        labelStyle={{ width: 200 }}
                        contentStyle={{ width: 200 }}
                        column={{ xxl: 4, xl: 4, lg: 4, md: 4, sm: 2, xs: 1 }}
                    >
                        <Descriptions.Item label={`${item.title}应收`}>{item.fee}</Descriptions.Item>
                        <Descriptions.Item label={`${item.title}实收`}>{item.pay}</Descriptions.Item>
                        <Descriptions.Item label="支付时间">{item.time}</Descriptions.Item>
                        <Descriptions.Item label="支付方式">{item.chargeWay}</Descriptions.Item>
                    </Descriptions>)
                })}
            </ProCard>
            <ProCard style={{ marginTop: 8 }} gutter={8}>
                <Title level={3}>通知信息</Title>
                {!!deliveryDetail?.notify && <ProTable
                    rowKey="sendTime"
                    search={false}
                    pagination={false}
                    toolBarRender={false}
                    columns={notice_columns}
                    dataSource={deliveryDetail?.notify}

                />}
            </ProCard>

            <ModalForm
                title={'修改手机号'}
                modalProps={{
                    centered: true,
                    destroyOnClose: true,
                }}
                width="950px"
                labelCol={{ span: 6 }}
                visible={updPhoneVisible}
                initialValues={{
                    ...deliveryDetail,
                    old_phone: deliveryDetail?.receiver.phone || '--',
                }}
                onVisibleChange={handleUpdPhoneVisible}
                layout={'horizontal'}
                onFinish={async (value) => {
                    const params = {
                        id: deliveryDetail.id,
                        phone: value.phone,
                    };
                    const msg = await changePhone(params);
                    if (msg.code === 0) {
                        message.success('修改成功!');
                        handleUpdPhoneVisible(false);
                    }
                }}
            >
                <Row gutter={16}>
                    <Col span={12} style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
                        <ProFormText
                            label='运单号'
                            disabled
                            rules={[
                                {
                                    required: true,
                                },
                            ]}
                            width="md"
                            name="billNo"
                        />
                        <ProFormText
                            label='入库时间'
                            disabled
                            rules={[
                                {
                                    required: true,
                                },
                            ]}
                            width="md"
                            name="checkinTime"
                        />
                        <ProFormText
                            label='原手机号'
                            disabled
                            rules={[
                                {
                                    required: true,
                                },
                            ]}
                            width="md"
                            name="old_phone"
                        />
                        <ProFormText
                            label='新手机号'
                            placeholder={'请输入新的客户手机号'}
                            rules={[
                                {
                                    required: true,
                                },
                                {
                                    len: 11,
                                },
                                ({ getFieldValue }) => ({
                                    validator(_, value) {
                                        if (value && getFieldValue('old_phone') === value) {
                                            return Promise.reject(new Error('新手机号不能与原手机号相同'));
                                        }
                                        return Promise.resolve();
                                    },
                                }),
                            ]}
                            width="md"
                            name="phone"
                        />
                        <div style={{ fontSize: 12, color: 'rgba(16, 16, 16, 100)', marginTop: 42, }}>注意：如订单需要支付取件费或延期费，修改手机号后将重新计费！</div>
                    </Col>
                    <Col span={12} style={{ display: 'flex', alignItems: 'center', flexDirection: 'column' }}>
                        <div style={{ width: '100%', padding: '10px 15%', display: 'flex', justifyContent: 'space-around', alignItems: 'center', fontSize: '32px', color: '#1890FF' }}>
                            <MyIcon type="icon-a-shunshizhenxuanzhuan90" onClick={() => {
                                handleUpdRotation(rotation + 90);
                            }} />
                            <MyIcon type="icon-a-nishizhenxuanzhuan90" onClick={() => {
                                handleUpdRotation(rotation - 90);
                            }} />
                            <MyIcon type="icon-a-shunshizhenxuanzhuan180" onClick={() => {
                                handleUpdRotation(rotation + 180);
                            }} />
                        </div>
                        <div style={{ width: 360, height: 360, overflow: 'hidden' }}>
                            {deliveryDetail?.ocrImageTimeout ? <div style={{ width: '100%', height: '100%', display: 'flex', justifyContent: 'center', alignItems: 'center', backgroundColor: '#E8E8E8' }}>图片已过期(保存30天)</div> : ((deliveryDetail?.ocrImage || deliveryDetail?.scanImg) ? <Image src={deliveryDetail?.ocrImage || deliveryDetail?.scanImg} style={{ width: 360, height: 360, transform: `scale3d(1, 1, 1) rotate(${rotation}deg)` }} alt="" /> : <div style={{ width: '100%', height: '100%', display: 'flex', justifyContent: 'center', alignItems: 'center', backgroundColor: '#E8E8E8' }}>该订单为手动输入，无入库底单</div>)}
                        </div>
                    </Col>
                </Row>

            </ModalForm>
        </PageContainer>
    );
};

export default Detail;
